Passed
Push — master ( 7c19a0...ad5e1b )
by Rafael S.
01:24
created

to-bytes.js ➔ toBytes   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 2
c 3
b 1
f 0
nc 2
nop 3
dl 0
loc 10
rs 9.4285
1
/*
2
 * to-bytes: bytes to numbers and strings.
3
 * Copyright (c) 2017 Rafael da Silva Rocha.
4
 * https://github.com/rochars/byte-data
5
 */
6
7
const writer = require("../src/write-bytes.js");
8
const helpers = require("../src/helpers.js");
9
10
/**
11
 * Turn numbers and strings to bytes.
12
 * @param {!Array<number>|number|string} values The data.
13
 * @param {number} bitDepth The bit depth of the data.
14
 *   Possible values are 1, 2, 4, 8, 16, 24, 32, 40, 48 or 64.
15
 * @param {Object} options The options:
16
 *   - "float": True for floating point numbers. Default is false.
17
 *       This option is available for 16, 32 and 64-bit numbers.
18
 *   - "base": The base of the output. Default is 10. Can be 2, 10 or 16.
19
 *   - "char": If the bytes represent a string. Default is false.
20
 *   - "be": If the values are big endian. Default is false (little endian).
21
 *   - "buffer": If the bytes should be returned as a Uint8Array.
22
 *       Default is false (bytes are returned as a regular array).
23
 * @return {!Array<number>|Uint8Array} the data as a byte buffer.
24
 */
25
function toBytes(values, bitDepth, options={"base": 10}) {
26
    values = helpers.turnToArray(values);
27
    let bytes = writeBytes(values, options.char, options.float, bitDepth);
28
    helpers.makeBigEndian(bytes, options.be, bitDepth);
29
    helpers.outputToBase(bytes, bitDepth, options.base);
30
    if (options.buffer) {
31
        bytes = new Uint8Array(bytes);
32
    }
33
    return bytes;
34
}
35
36
/**
37
 * Write values as bytes.
38
 * @param {!Array<number>|number|string} values The data.
39
 * @param {boolean} isChar True if it is a string.
40
 * @param {boolean} isFloat True if it is a IEEE floating point number.
41
 * @param {number} bitDepth The bitDepth of the data.
42
 * @return {!Array<number>} the bytes.
43
 */
44
function writeBytes(values, isChar, isFloat, bitDepth) {
45
    let bitWriter;
46
    if (isChar) {
47
        bitWriter = writer.writeString;
48
    } else {
49
        bitWriter = writer['write' + bitDepth + 'Bit' + (isFloat ? "Float" : "")];
50
    }
51
    let i = 0;
52
    let j = 0;
53
    let len = values.length;
54
    let bytes = [];
55
    while (i < len) {            
56
        j = bitWriter(bytes, values, i, j);
57
        i++;
58
    }
59
    return bytes;
60
}
61
62
module.exports.toBytes = toBytes;
63